import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';

class YhzlhcView extends BaseStatefulWidget {

  final String id;
  YhzlhcView({this.id});

  @override
  State<StatefulWidget> initState() {
    return YhzlhcViewState();
  }
}

class YhzlhcViewState extends BaseState<YhpcViewModel, YhzlhcView> {

  TextEditingController _hcyjCtr = TextEditingController(); // 核查意见
  TextEditingController _jyyyCtr = TextEditingController(); // 简要原因
  TextEditingController _gszyCtr = TextEditingController(); // 归属专业
  TextEditingController _zlcsCtr = TextEditingController(); // 治理措施
  TextEditingController _zrrCtr = TextEditingController(); // 责任人
  TextEditingController _zgqxCtr = TextEditingController(); // 整改完成期限
  TextEditingController _yhzrbmCtr = TextEditingController(); // 隐患责任部门


  TextEditingController _zlffCtr = TextEditingController(); // 采取方法
  TextEditingController _zljfCtr = TextEditingController(); // 治理经费
  TextEditingController _zlrwCtr = TextEditingController(); // 治理任务
  TextEditingController _zlmbCtr = TextEditingController(); // 治理目标

  String _selDjlx = 'ybyh';
  String _selYhdj = 'generalHazard';
  String _selzglxData = 'immediatelyRectify';
  String _selOrgCode = '';
  String _selPersonOpenId = '';


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _zgqxCtr.text = DateUtil.getDateStrByDateTime(DateTime.parse(DateTime.now().toString()),
              format: DateFormat.YEAR_MONTH_DAY_HOUR_MINUTE) + ':00';
    if(!StringUtils.isEmpty(widget.id)) {
      _initData();
    }
  }

  @override
  Widget initWidget() {
    return Scaffold(
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '核查',
      ).create(),
      body: _bodyView(),
    );
  }


  _initData() {
    viewModel.yhzlListDetail(widget.id);
    viewModel.yhzlListDetailStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          var _dataM = event['data'];


          _hcyjCtr.text =  StringUtils.getStr(_dataM['verifyOpinionDescription']);
          _jyyyCtr.text =  StringUtils.getStr(_dataM['reasonAnalyzeDescription']);
          _gszyCtr.text =  StringUtils.getStr(_dataM['hazardProfessionName']);
          _zlcsCtr.text = StringUtils.getStr(_dataM['hazardGovernMeasure']);

          _selzglxData =  StringUtils.isEmpty(_dataM['rectifyType']) ? 'immediatelyRectify' : StringUtils.getStr(_dataM['rectifyType']);
          _zgqxCtr.text =  StringUtils.getStr(_dataM['rectifyCompleteDeadlineTime']);
          _zlmbCtr.text =  StringUtils.getStr(_dataM['hazardGovernTarget']);
          _zlrwCtr.text =  StringUtils.getStr(_dataM['hazardGovernTask']);
          _zlffCtr.text =  StringUtils.getStr(_dataM['hazardGovernMethod']);
          _zljfCtr.text =  StringUtils.getStr(_dataM['hazardGovernMaterial']);



          _yhzrbmCtr.text =  StringUtils.getStr(_dataM['rectifyResponsibleOrgCodeName']);
          _zrrCtr.text = StringUtils.getStr(_dataM['rectifyResponsiblePersonName']);
          _selPersonOpenId = StringUtils.getStr(_dataM['rectifyResponsiblePersonOpenId'].toString());
          _selOrgCode =  StringUtils.getStr(_dataM['rectifyResponsibleOrgCode'].toString());


        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  _bodyView() {
    return Container(
      child: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.all(15),
              decoration: BoxDecoration(
                  borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                  color: SQColor.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                JText(
                                  '* ',
                                  color: SQColor.red,
                                ),
                                Container(
                                  child: JText('核查结果'),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 10),
                            child: Row(
                              children: [
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selDjlx = 'ybyh';
                                        _selYhdj = 'generalHazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selYhdj == 'generalHazard'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                              BorderRadius.circular(8)),
                                      child: JText('一般隐患',
                                          color: _selYhdj == 'generalHazard'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selDjlx = 'zdyh';
                                        _selYhdj = 'majorHazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color:  _selYhdj == 'majorHazard'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                              BorderRadius.circular(8)),
                                      child: JText('重大隐患',
                                          color: _selYhdj == 'majorHazard'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selDjlx = 'bsyh';
                                        _selYhdj = 'notHazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selYhdj == 'notHazard'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                              BorderRadius.circular(8)),
                                      child: JText('不是隐患',
                                          color: _selYhdj == 'notHazard'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    _selDjlx == 'bsyh' ?
                    _commField(
                      isMust: true,
                      controller: _hcyjCtr,
                      title: '核查意见',
                      hintText: '请输入核查意见',
                      maxLength: 200,
                    ) : _yborzdView(),
                    Container(
                      height: 20,
                    ),
                  ],
                ),
              ),
            ),
          ),
          _bottomView()
        ],
      ),
    );
  }

  _yborzdView() {
    return Column(children: [
      _commField(
        controller: _hcyjCtr,
        title: '核查意见',
        hintText: '请输入核查意见',
        maxLength: 200,
      ),
      _commField(
        controller: _jyyyCtr,
        title: '简要原因',
        hintText: '请输入简要原因分析',
        maxLength: 500,
      ),
      _commField(
        isMust: false,
        controller: _gszyCtr,
        title: '隐患归属专业',
        hintText: '请输入隐患归属专业',
      ),
      _selDjlx == 'zdyh' ? _commField( isMust: true,
        controller: _zlmbCtr,
        title: '隐患治理目标',
        hintText: '请输入隐患治理目标',
        maxLength: 500,
      ) : Container(),
      _selDjlx == 'zdyh' ? _commField(isMust: true,
        controller: _zlrwCtr,
        title: '隐患治理任务',
        hintText: '请输入隐患治理任务',
        maxLength: 500,
      ) : Container(),
      _selDjlx == 'zdyh' ? _commField(isMust: true,
        controller: _zlffCtr,
        title: '采取方法',
        hintText: '请输入采取方法',
        maxLength: 500,
      ) : Container(),
      _selDjlx == 'zdyh' ? _commField(isMust: true,
        controller: _zljfCtr,
        title: '治理经费和物质',
        hintText: '请输入治理经费和物质',
        maxLength: 500,
      ) : Container(),
      _commField(
        isMust: true,
        title: '隐患治理措施',
        controller: _zlcsCtr,
        hintText: '请选择隐患治理措施',
        maxLength: 500,
      ),
      _commField(
          isMust: true,
          title: '隐患整改责任部门',
          controller: _yhzrbmCtr,
          hintText: '请选择隐患整改责任部门',
          isReadOnly: true,
          suffixIcon: Icon(
            Icons.arrow_forward_ios_outlined,
            size: Dimens.dimens15,
            color: SQColor.black_999999,
          ),
          onTap: () {
            Navigator.pushNamed(context, '/ChooseBuMen')
                .then((value) {
              if (value != null) {
                Map map1 = value;
                _selOrgCode = map1['orgCode'];
                _yhzrbmCtr.text =
                value == null ? '' : map1['orgName'];
                _selPersonOpenId = '';
                _zrrCtr.text = "";
              }
            });
          }),
      _commField(
          isMust: true,
          title: '隐患整改责任人',
          hintText: '请选择隐患整改责任人',
          controller: _zrrCtr,
          isReadOnly: true,
          suffixIcon: Icon(
            Icons.arrow_forward_ios_outlined,
            size: Dimens.dimens15,
            color: SQColor.black_999999,
          ),
          onTap: () {
            Navigator.pushNamed(context, '/ChoosePersonDan',
                arguments: _selOrgCode)
                .then((value) {
              if (value != null) {
                Map map = value;
                _selPersonOpenId = map['openId'];
                _zrrCtr.text = map['name'];
              }
            });
          }),

      Container(
        margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
        child: Column(
          children: [
            Container(
              child: Row(
                children: [
                  JText(
                    '* ',
                    color: SQColor.red,
                  ),
                  Container(
                    child: JText('整改类型'),
                  ),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 10),
              child: Row(
                children: [
                  Expanded(
                    child: InkWell(
                      onTap: () {
                        setState(() {
                          _selzglxData = 'immediatelyRectify';
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.only(right: 5),
                        height: 35,
                        decoration: BoxDecoration(
                            color:
                            _selzglxData == 'immediatelyRectify'
                                ? SQColor.theme_color
                                : SQColor.white,
                            border: Border.all(
                              width: 1,
                              color: SQColor.theme_color,
                            ),
                            borderRadius:
                            BorderRadius.circular(8)),
                        child: JText('立即整改',
                            color:
                            _selzglxData == 'immediatelyRectify'
                                ? SQColor.white
                                : SQColor.theme_color,
                            fontSize: 14),
                      ),
                    ),
                  ),
                  Expanded(
                    child: InkWell(
                      onTap: () {
                        setState(() {
                          _selzglxData = 'deadlineRectify';
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.only(right: 5),
                        height: 35,
                        decoration: BoxDecoration(
                            color: _selzglxData == 'deadlineRectify'
                                ? SQColor.theme_color
                                : SQColor.white,
                            border: Border.all(
                              width: 1,
                              color: SQColor.theme_color,
                            ),
                            borderRadius:
                            BorderRadius.circular(8)),
                        child: JText('限期整改',
                            color: _selzglxData == 'deadlineRectify'
                                ? SQColor.white
                                : SQColor.theme_color,
                            fontSize: 14),
                      ),
                    ),
                  ),
                  Expanded(
                    child: InkWell(
                      onTap: () {
                        setState(() {
                          _selzglxData = 'stopBusinessRectify';
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.only(right: 5),
                        height: 35,
                        decoration: BoxDecoration(
                            color: _selzglxData == 'stopBusinessRectify'
                                ? SQColor.theme_color
                                : SQColor.white,
                            border: Border.all(
                              width: 1,
                              color: SQColor.theme_color,
                            ),
                            borderRadius:
                            BorderRadius.circular(8)),
                        child: JText('停产停业整顿',
                            color: _selzglxData == 'stopBusinessRectify'
                                ? SQColor.white
                                : SQColor.theme_color,
                            fontSize: 14),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      _commField(
          isMust: true,
          controller: _zgqxCtr,
          title: '完成期限',
          hintText: '请选择完成期限',
          isReadOnly: true,
          suffixIcon: Image.asset(
            "img/field_date.png",
            width: Dimens.dimens15,
            height: Dimens.dimens15,
          ),
          onTap: () {
            _datePicker(true);
          }),
    ],);
  }


  _datePicker(bool isStart) {
    String jbTime = '';
    showDatePicker(
      context: context,
      initialDate: new DateTime.now(), // 加 30 天
      firstDate:
      new DateTime.now().subtract(new Duration(days: 3650)), // 减 30 天
      lastDate: new DateTime.now().add(new Duration(days: 3650)),
    ).then((DateTime val) {
      showTimePicker(
        context: context,
        initialTime: new TimeOfDay.now(),
      ).then((val1) {
        if (val1 == null) {
          return;
        }
        setState(() {
          jbTime = DateUtil.getDateStrByDateTime(DateTime.parse(val.toString()),
              format: DateFormat.YEAR_MONTH_DAY);
          String hour1 = val1.hour < 10
              ? "0" + val1.hour.toString()
              : val1.hour.toString();
          String hour2 = val1.minute < 10
              ? "0" + val1.minute.toString()
              : val1.minute.toString();

          jbTime = jbTime +
              " " +
              hour1 +
              ":" +
              hour2 +
              ":" +
              "00"; // 2018-07-12 00:00:00.000018-07-12 00:00:00.000
          if (isStart) {
            _zgqxCtr.text = jbTime;
          } else {
            _zgqxCtr.text = jbTime;
          }
        });
      }).catchError((err) {
        print(err);
      });
    }).catchError((err) {
      print(err);
    });
  }


  _bottomView() {
    return Row(
      children: [
        Expanded(
          child: InkWell(
            onTap: () {
              _done();
            },
            child: SafeArea(
              child: Container(
                margin: EdgeInsets.only(left: 15, right: 15),
                height: 45,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: SQColor.theme_color,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: JText('确定', color: Colors.white),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 提交保存
  _done() {
    if(_selDjlx == 'ybyh') {
      if(_zlcsCtr.text.isEmpty) {
        ToastUtils.showToast('请填写治理措施');
        return;
      }
      if(_selOrgCode.isEmpty) {
        ToastUtils.showToast('请填写隐患整改责任部门');
        return;
      }
      if(_selPersonOpenId.isEmpty) {
        ToastUtils.showToast('请填写隐患整改责任人');
        return;
      }
      if(_zgqxCtr.text.isEmpty) {
        ToastUtils.showToast('请填写隐患整改期限');
        return;
      }
    }else if(_selDjlx == 'zdyh') {
      if(_zlcsCtr.text.isEmpty) {
        ToastUtils.showToast('请填写治理措施');
        return;
      }
      if(_selOrgCode.isEmpty) {
        ToastUtils.showToast('请填写隐患整改责任部门');
        return;
      }
      if(_selPersonOpenId.isEmpty) {
        ToastUtils.showToast('请填写隐患整改责任人');
        return;
      }
      if(_zgqxCtr.text.isEmpty) {
        ToastUtils.showToast('请填写隐患整改期限');
        return;
      }
      if(_zlrwCtr.text.isEmpty) {
        ToastUtils.showToast('请填写隐患治理任务');
        return;
      }
      if(_zlmbCtr.text.isEmpty) {
        ToastUtils.showToast('请填写隐患治理目标');
        return;
      }
      if(_zlffCtr.text.isEmpty) {
        ToastUtils.showToast('请填写采取方法');
        return;
      }
      if(_zljfCtr.text.isEmpty) {
        ToastUtils.showToast('请填写治理经费和物质');
        return;
      }
    }else {
      if(_hcyjCtr.text.isEmpty) {
        ToastUtils.showToast('请填写核查意见');
        return;
      }
    }
    _submit();
  }

  _submit() {
    var map = {
      'hazardId': widget.id,
      'verifyOpinionDescription': _hcyjCtr.text,
      'reasonAnalyzeDescription': _jyyyCtr.text,
      'hazardProfessionName': _gszyCtr.text,
      'hazardGovernMeasure': _zlcsCtr.text,
      'rectifyResponsiblePersonOpenId': _selPersonOpenId,
      'rectifyResponsibleOrgCode': _selOrgCode,
      'verifyResultType' : _selYhdj,
      'rectifyType': _selzglxData,
      'rectifyCompleteDeadlineTime': _zgqxCtr.text.isEmpty ? null : _zgqxCtr.text,
      'hazardGovernTarget': _zlmbCtr.text,
      'hazardGovernTask': _zlrwCtr.text,
      'hazardGovernMethod': _zlffCtr.text,
      'hazardGovernMaterial': _zljfCtr.text,
    };
    ToastUtils.showLoading();
    viewModel.yhhc(map);
    viewModel.yhhcDataStream().listen((event) {
      ToastUtils.dissLoading();
      if (event['code'] == '0') {
        ToastUtils.showToast('提交成功');
        Navigator.of(context)..pop()..pop();
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      ToastUtils.dissLoading();
      print(e);
    });
  }

  _commField(
      {bool isMust = false,
      String hintText = '',
      Widget suffixIcon,
      String title = '',
      bool isReadOnly = false,
      int maxLength,
      var onTap,
      var controller}) {
    return Container(
      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
      child: Column(
        children: [
          Container(
            child: Row(
              children: [
                isMust
                    ? JText(
                        '* ',
                        color: SQColor.red,
                      )
                    : Container(),
                Container(
                  child: JText(title),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(
                left: 10,
                right: maxLength == null ? 0 : 10,
                bottom: maxLength == null ? 0 : 10),
            child: TextField(
              controller: controller,
              onTap: onTap,
              maxLength: maxLength,
              readOnly: isReadOnly,
              style: TextStyle(fontSize: Dimens.textSize28),
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: hintText,
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  suffixIcon: suffixIcon),
            ),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: SQColor.lineE7E7E7,
              ),
              borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens4)),
            ),
          ),
        ],
      ),
    );
  }
}
